/**
 * 
 */
package by.wind.drebedengi;

import java.util.ArrayList;
import java.util.Calendar;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.RuntimeExceptionDao;

import by.wind.drebedengi.asynctask.AsyncTaskManager;
import by.wind.drebedengi.asynctask.UploadAsyncTask;
import by.wind.drebedengi.database.MyDatabaseHelper;
import by.wind.drebedengi.datalayer.Constants;
import by.wind.drebedengi.datalayer.bean.Currency;
import by.wind.drebedengi.datalayer.bean.Place;
import by.wind.drebedengi.datalayer.bean.Record;
import by.wind.drebedengi.datalayer.bean.Source;
import by.wind.drebedengi.utils.Convertor;
import by.wind.drebedengi.utils.PrefUtil;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * @author wind
 *
 */
public class IncomingActivity extends  OrmLiteBaseActivity<MyDatabaseHelper> {

	private Spinner itsPlaceView;
	private Spinner itsSourceView;
	private Spinner itsCurrencyView;
	private EditText itsTag;
	private EditText itsSum;
	
	private ArrayList<Place>    itsPlaceList    = new ArrayList<Place>();
	private ArrayList<Source>    itsSourceList    = new ArrayList<Source>();
	private ArrayList<Currency> itsCurrencyList = new ArrayList<Currency>();
	
	private AsyncTaskManager itsAsyncTaskManager;
	
	private static int CURRENT_HOUR = 23;
    private static int CURRENT_MINUTE = 59;
    private static int CURRENT_SECOND = 59;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.incoming_tab);
		
		itsAsyncTaskManager = new AsyncTaskManager(this, (MainActivity)this.getParent());
		itsAsyncTaskManager.handleRetainedTask(getLastNonConfigurationInstance());
		
		Button saveButton = (Button) findViewById(R.id.incoming_save);
		itsTag = (EditText) findViewById(R.id.incoming_tag);
        itsSum = (EditText) findViewById(R.id.incoming_sum_edit_text);
		saveButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				/* Datetime */
				
		        DatePicker datePicker = (DatePicker) findViewById(R.id.datePickerIncoming);
		        Calendar calendar = Calendar.getInstance();
		        calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
		        calendar.set(Calendar.MONTH, datePicker.getMonth());
		        calendar.set(Calendar.YEAR, datePicker.getYear());
		        calendar.set(Calendar.HOUR_OF_DAY, CURRENT_HOUR);
		        calendar.set(Calendar.MINUTE, CURRENT_MINUTE);
		        calendar.set(Calendar.SECOND, CURRENT_SECOND);
		        
		        
		        if (itsSum.getText().length() == 0) {
		        	showTraces(getString(R.string.emptysum_message));
		        	return;
		        } else if (itsSourceView.getSelectedItem()== null) {
		        	showTraces(getString(R.string.outgoing_emptycategory_message));
		        	return;
		        } else if (itsPlaceView.getSelectedItem()== null) {
		        	showTraces(getString(R.string.emptyplace_message));
		        	return;
		        }
		        	
		        String sourceString = "";
		        if (itsSourceView.getSelectedItem()!= null)
		        	sourceString = itsSourceView.getSelectedItem().toString();
		        Record record = new Record();
		        record.setOperation_date(calendar.getTime());
		        record.setComment(itsTag.getText().toString());
		        record.setSum(Long.valueOf(itsSum.getText().toString()) * Record.QUALIFICATION);
		        record.setSource(retrieveSourceByName(sourceString));
		        record.setOperation_type(Constants.OPERATION_INCOME);
		        String placeString = "";
		        if (itsPlaceView.getSelectedItem()!= null) {
		        	placeString = itsPlaceView.getSelectedItem().toString();
		        }
		        record.setPlace(retrievePlaceByName(placeString));
		        if (itsCurrencyView.getSelectedItem() != null)
		        	record.setCurrency(retrieveCurrencyByName(itsCurrencyView.getSelectedItem().toString()));
		        else
		        	showTraces(getString(R.string.emptycurrency_message));
		        getHelper().save(record);
		        
		        resetForm();
		        itsAsyncTaskManager.setupTask(new UploadAsyncTask(IncomingActivity.this));
			}
		});
		/*itsSum.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View view, boolean hasFocus) {
				// TODO Auto-generated method stub
				EditText sumView = (EditText) findViewById(R.id.incoming_sum_edit_text);
				if (!hasFocus && sumView.getText().length()>0) {
					
					sumView.setText(Convertor.convert(sumView.getText().toString()).toString());
				}
			}
			
		});*/
		loadFormData();
	}

	private void resetForm() {
		// save current elements state
        PrefUtil.saveSpinnerState(IncomingActivity.this, itsCurrencyView);
		itsSourceView.setSelection(0);
    	itsTag.setText(null);
    	itsSum.setText(null);
    }
	
	protected void loadFormData() {
		Log.e("Drebedengi", "IncomingActivity.loadFormData()");
		RuntimeExceptionDao<Currency,Integer> currencyDao = getHelper().getCurrencyDataDao();
    	itsCurrencyList = (ArrayList<Currency>)currencyDao.queryForAll();
    	String[] currencyItems = new String[itsCurrencyList.size()];
    	for(int i = 0; i<itsCurrencyList.size(); i++) {
    		currencyItems[i] = itsCurrencyList.get(i).getName();
    	}
    	ArrayAdapter<String> currencyAdapter = new ArrayAdapter<String>(IncomingActivity.this, android.R.layout.simple_spinner_item, currencyItems);
    	currencyAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    	itsCurrencyView = (Spinner) findViewById(R.id.incoming_currency);
    	itsCurrencyView.setAdapter(currencyAdapter);
    	// restore current currency
    	itsCurrencyView.setSelection(PrefUtil.loadSpinnerState(this, itsCurrencyView));
		
		RuntimeExceptionDao<Place,Integer> placeDao = getHelper().getPlaceDataDao();
    	itsPlaceList = (ArrayList<Place>) placeDao.queryForAll();
    	String[] placeItems = new String[itsPlaceList.size()];
    	for(int i = 0; i<itsPlaceList.size(); i++) {
    		placeItems[i] = itsPlaceList.get(i).getName();
    	}
    	ArrayAdapter<String> placeAdapter = new ArrayAdapter<String>(IncomingActivity.this, android.R.layout.simple_spinner_item, placeItems);
    	itsPlaceView = (Spinner) findViewById(R.id.incoming_place);
    	itsPlaceView.setAdapter(placeAdapter);
    	
    	RuntimeExceptionDao<Source,Integer> sourceDao = getHelper().getSourceDataDao();
    	itsSourceList = (ArrayList<Source>) sourceDao.queryForAll();
    	String[] sourceItems = new String[itsSourceList.size()];
    	for(int i = 0; i<itsSourceList.size(); i++) {
    		sourceItems[i] = itsSourceList.get(i).getName();
    	}
    	ArrayAdapter<String> sourceAdapter = new ArrayAdapter<String>(IncomingActivity.this, android.R.layout.simple_spinner_item, sourceItems);
    	itsSourceView = (Spinner) findViewById(R.id.incoming_source);
    	itsSourceView.setAdapter(sourceAdapter);
	}
	
	private void showTraces(String log) {
    	(Toast.makeText(this, log, Toast.LENGTH_LONG)).show();
    }
	
	private Source retrieveSourceByName(String aName) {
    	for(Source element : itsSourceList) {
    		if (element != null && element.getName().equals(aName))
    			return element;
    	}
    	return null;
    }
    
    private Currency retrieveCurrencyByName(String aName) {
    	for(Currency element : itsCurrencyList) {
    		if (element != null && element.getName().equals(aName))
    			return element;
    	}
    	return null;
    }
    
    @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	private Place retrievePlaceByName(String aName) {
    	for(Place element : itsPlaceList) {
    		if (element != null && element.getName().equals(aName))
    			return element;
    	}
    	return null;
    }
	
	@Override
    public Object onRetainNonConfigurationInstance() {
		return itsAsyncTaskManager.retainTask();
    }
}
